use bevy::{
    asset,
    prelude::{AddAsset, AppBuilder, AssetServer, Plugin},
    tasks::IoTaskPool,
};

use self::{
    pal::{Pal, PalLoader},
    shp::{Shp, ShpLoader},
};

mod convert;
pub mod pal;
pub mod shp;

pub struct OpenRAAssetPlugin;

impl Plugin for OpenRAAssetPlugin {
    fn build(&self, app: &mut AppBuilder) {
        if app.world().get_resource::<AssetServer>().is_none() {
            let task_pool = app
                .world()
                .get_resource::<IoTaskPool>()
                .expect("`IoTaskPool` resource not found.")
                .0
                .clone();

            let source = asset::create_platform_default_asset_io(app);

            let asset_server = AssetServer::with_boxed_io(source, task_pool);
            asset_server.add_loader(PalLoader::default());
            asset_server.add_loader(ShpLoader::default());
            app.insert_resource(asset_server);
        } else {
            let asset_server = app.world_mut().get_resource_mut::<AssetServer>().unwrap();
            asset_server.add_loader(PalLoader::default());
            asset_server.add_loader(ShpLoader::default());
        }

        app.add_asset::<Pal>();
        app.add_asset::<Shp>();
    }
}
